// pages/workerCode/search.js
Page({

  data: {
    history: [],
    showActionSheet: false,
    tips: "确认清空搜索历史吗？",
    popupShow: false,
    popupItem:{title:'',user:{}},
    timeArea:{},
    list:[],
    isEmpty:false,
    sub:{key:'',cate:99,latitude:0,longitude:0,page:1},
  },
  onShow(){
    this.setData({
      history:this.getHistory()
    })
  },
  onLoad: function(e) {
    this.setData({
      'sub.longitude':e.longitude,
      'sub.latitude':e.latitude
    })
    this.loadTime();
  },
  watch:{
    'sub.key':{
      handler(n,o){
        if(n==""){
          this.list=[];
        }
      }
    }
  },
  acPop(e){
    if(e.type=="刷新"){
      this.load();
      return;
    }
  },
  btnclick(e){
    if(e.type=="more"){
      this.setData({
        popupItem:e.data,
        popupShow:true
      })
    }
  },
  async loadTime(){
    let res=await wx.util.post("task/get_time");
    this.setData({
      timeArea:res.data
    })
  },
  async load(){
    this.setData({
      isEmpty:false
    })
    let res=await wx.util.post("task/index",this.data.sub,false);
    this.setData({
      list:res.data.data
    })
    if(this.data.sub.page==1 && this.data.list.length==0){
      this.setData({
        isEmpty:true
      })
    }
  },
  getHistory(){
    let data=wx.getStorageSync("worker_history") || "[]";
    return JSON.parse(data);
  },
  setHistory(){
    let data=this.getHistory();
    if(data.indexOf(this.data.sub.key)<0){
      data.push(this.data.sub.key);
      wx.setStorageSync("worker_history",JSON.stringify(data));
    }
  },
  keyTap(e){
    let key=e.currentTarget.dataset.item;
    this.setData({
      'sub.key':key
    })
    this.load();
  },
  gotoSearch(){
    if(this.data.sub.key==""){
      wx.util.toast('关键词不能为空');
      return;
    }
    this.setHistory();
    this.load();
  },
  back: function() {
    wx.navigateBack();
  },
  cleanKey: function() {
    this.setData({
      'sub.key': '',
      list:[],
      isEmpty:false
    })
  },
  closeActionSheet: function() {
    this.setData({
      showActionSheet: false
    })
  },
  openActionSheet: function() {
    this.setData({
      showActionSheet: true
    })
  },
  itemClick: function(e) {
    let index = e.detail.index;
    if (index == 0) {
      this.setData({
        showActionSheet: false,
        history: []
      })
      wx.removeStorageSync("worker_history");
    }
  },
  inputKey: function(e) {
    this.setData({
      'sub.key': wx.util.trim(e.detail.value)
    })
  },
  setPopupShow(){
    this.setData({
      popupShow:!this.datga.popupShow
    })
  }
})